const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
const tfx = require('./transformXlsx');
const { defaultLanguage } = require('../config');

const filePath = path.join(__dirname, '../source');
const fileNames = fs.readdirSync(filePath);
var iSheet = []
const languageObjModal = {
    "English": "en",
    "Chinese": "cn",
    "Bahasa Indonesia": "id",
    "Thai": "th",
    "Vietnamese": "vn",
    "Japanese": "jp",
    "Spanish": "es",
    "Portuguese": "pt"
}
const languageTopModal = {
    "English": "en",
    "Chinese": "cn",
    "Bahasa Indonesia": "en",
    "Thai": "en",
    "Vietnamese": "en",
    "Japanese": "en",
    "Spanish": "en",
    "Portuguese": "en"
}
function getLanguageObj(languageKey) {
    let data = {}
    for (let item of iSheet) {
        data[item.English] = item[languageKey]
    }
    return data
}
// 批量替换语言
function replaceLanguage(file, languageObj, outputFilePath, key, resolve) {
    const $ = cheerio.load(file);
    // 遍历所有文本节点，进行替换
    let rule = '*:not(script)'
    $(rule).contents().each((index, element) => {
        if (element.nodeType === 3) { // 文本节点
            let originalText = element.nodeValue;
            let originalTextTrim = originalText.trim();
            let newTextTrim = languageObj[originalTextTrim];
            if (newTextTrim) {
                let newText = originalText.replace(originalTextTrim, newTextTrim);
                element.nodeValue = newText;
            }
        }
    });
    let result = $.html();
    const outputFileFatherPath = path.join(__dirname, `../output/${languageObjModal[key]}`);
    // console.log("outputFileFatherPath==", outputFileFatherPath);
    // if (fs.existsSync(outputFileFatherPath)) {
    //     fs.unlinkSync(outputFileFatherPath);
    // }
    fs.writeFile(outputFilePath, result, 'utf-8', (err) => {
        if (err) {
            console.log(`${outputFilePath} replacement successful`)
        } else {
            console.log(`${outputFilePath} replacement failed` + err)
        }
        resolve()
    });
}
function init({ needFilterJs }) {
    // 遍历文件列表
    fileNames.forEach((fileName) => {
        const filePath = path.join(__dirname, `../source/${fileName}`);
        const SheetN = fs.readFileSync(filePath, 'utf-8');
        // 拿到html文件的字符串
        let Sheet = JSON.parse(JSON.stringify(SheetN))
        for (let key in languageObjModal) {
            const languageObj = getLanguageObj(key)
            const outputFilePath = path.join(__dirname, `../output/${languageObjModal[key]}/${fileName}`);
            // console.log("language==",key,'==',languageObj);
            replaceLanguage(Sheet, languageObj, outputFilePath, key, () => {
                let keySheet = fs.readFileSync(outputFilePath, 'utf-8');
                if (needFilterJs && key !== defaultLanguage) {
                    for (let item in languageObj) {
                        // if (key == 'Portuguese' && item == 'Trades successfully executed') {
                        //     console.log("item==", "'" + item + "'", '======', Sheet);
                        // }
                        // if (keySheet.indexOf("'" + item + "'") !== -1) {
                        //     keySheet = keySheet.replace("'" + item + "'", "'" + languageObj[item].replace('\n','').trim() + "'")
                        //     // console.log(item, '==', key, '==', languageObj[item]);
                        // }

                        if (keySheet.indexOf(item) !== -1) {
                            keySheet = keySheet.replaceAll(item, languageObj[item].replace('\n', '').trim())
                            // console.log(item, '==', key, '==', languageObj[item]);
                        }
                    }
                    fs.writeFile(outputFilePath, keySheet, 'utf-8', (err) => {
                        if (err) {
                            console.log(`${outputFilePath} replacement successful`)
                        } else {
                            console.log(`${outputFilePath} replacement failed` + err)
                        }
                    });
                }

            });
        }
        console.log('2s后自动替换头部语言====')
        setTimeout(() => {
            console.log('开始自动替换头部语言====')
            //替换顶部语言 <html lang="en">
            for (let key in languageObjModal) {
                const outputFilePath = path.join(__dirname, `../output/${languageObjModal[key]}/${fileName}`);
                let keySheet = fs.readFileSync(outputFilePath, 'utf-8');
                keySheet = keySheet.replace('<html lang="en">', `<html lang="${languageTopModal[key]}">`)
                keySheet = keySheet.replace('wetrade-res=""', `wetrade-res `)
                keySheet = keySheet.replace(/(<meta[^>]*)(>)/g, '$1/>');
                keySheet = keySheet.replace(/(<link[^>]*)(>)/g, '$1/>');
                fs.writeFile(outputFilePath, keySheet, 'utf-8', (err) => {
                    if (err) {
                        console.log(`${outputFilePath} replacement failed` + err)
                    } else {
                        console.log(`${outputFilePath} replacement successful`)
                    }
                });
            }
        }, 2000);
    });
}
//js是否需要过滤
const needFilterJs = true;
//先把excel文件转换为json文件
iSheet = tfx.transformXlsx()
//开始替换文本 并且生成html文件
init({ needFilterJs: needFilterJs })

